package systemRepository

import (
	"CommonsProject/models/systemModel"
	"CommonsProject/pkg/tools/bcryptTool"
	"CommonsProject/pkg/tools/sqlTool"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"log"
	"strings"
)

type SysUserRepository struct {
	DB *gorm.DB
}

// AddSysUser 添加用户
func (repository *SysUserRepository) AddSysUser(user *systemModel.SysUser) {
	//对密码进行加密
	pwd := bcryptTool.GetPwd(*user.Password)
	user.Password = &pwd

	result := repository.DB.Create(user)
	if result.Error != nil {
		panic(errors.New("添加用户失败！" + result.Error.Error()))
	}
}

// RemoveSysUser 删除用户
func (repository *SysUserRepository) RemoveSysUser(userId int) {
	result := repository.DB.Delete(&systemModel.SysUser{}, userId)
	if result.Error != nil {
		panic(errors.New("删除用户失败！" + result.Error.Error()))
	}
}

// ModifySysUser 修改用户
func (repository *SysUserRepository) ModifySysUser(user *systemModel.SysUser) {
	result := repository.DB.Save(user)
	if result.Error != nil {
		panic(errors.New("修改用户失败！" + result.Error.Error()))
	}
}

// FindSysUserById 查找用户通过ID
func (repository *SysUserRepository) FindSysUserById(userId uint) *systemModel.SysUser {
	var user *systemModel.SysUser
	repository.DB.Take(&user, userId)
	return user
}

// FindSysUser 查找用户
func (repository *SysUserRepository) FindSysUser(user *systemModel.SysUser, pageNum, pageSize int) sqlTool.PageInfo {
	generatorSQL, args, err := sqlTool.GeneratorSQL(*user)
	if err != nil {
		log.Panicln("生成SQL失败：", err)
	}

	sqlLimit := generatorSQL + fmt.Sprintf(" limit %d offset %d", pageSize, pageSize*(pageNum-1))
	var list []*systemModel.SysUser
	repository.DB.Raw(sqlLimit, args...).Scan(&list)

	//优化一下
	generatorSQL = strings.Replace(generatorSQL, " * ", " count(1) ", 1)
	var count int64
	repository.DB.Raw(generatorSQL, args...).Count(&count)
	return sqlTool.ToPageStruct(list, pageNum, pageSize, count)
}

// LoginUser 登录方法 特殊
func (repository *SysUserRepository) LoginUser(user *systemModel.SysUser) {
	repository.DB.First(&user)
}
